import {
  api,
  util,
  storage
} from "../util.js"
import authorize from './authorize.js'
import {router} from '../router';
const wholesale_settings_config ="wholesale_settings_config"
class WholesaleSettings {
  // 构造函数
  constructor(config) {
    config = config||{};
    this.priceDigits = config.PriceDigits||2;
    this.quantityDigits = config.QuantityDigits||2;
    this.decimalDigits = config.DecimalDigits || 2;
    this.openComment = config.OpenComment||false;
    this.freightMode = config.FreightMode||1;
    this.isStoreAffirmOrder = config.IsStoreAffirmOrder || false;
    this.allOrderAudit = config.AllOrderAudit || false;
    this.cODOrderAudit = config.CODOrderAudit || false;
    this.offlinePayOrderAudit = config.OfflinePayOrderAudit || false;
    this.SiteName = config.SiteName || false;
    this.CloseBuyerCancel = config.CloseBuyerCancel || false;
  }
  static setConfig(config){
    var entity =new WholesaleSettings(config);
    storage.put(wholesale_settings_config, entity, 0);
  }
  static getConfig() {
    var obj = storage.get(wholesale_settings_config);
    if (obj != null && obj != undefined && obj != "") {
      return obj;
    }
    return null;
  }
  static getDefault(){
    return {
      priceDigits:2,
      quantityDigits:2
    }
  }
}
/**
 *
 *core模块下使用
 *如：配置、域名相关的
 *
 */
module.exports = {
  domain: {
    /**
     * 获得域名
     */

    getDomain: function(callback) {
      let ext = wx.getExtConfigSync();
      
    if (ext && ext.attr) {
        let fkFlag=parseInt(ext.attr.fkFlag);
        let fkId=parseInt(ext.attr.fkId);
        var data = {
          "FKId": fkId,
          "FKFlag": fkFlag
        };
        util.post("social.minappoutline.config", data, function(res) {
          res = res.data;
          if (callback != undefined && typeof(callback) == "function") {
            callback(res);
          }
        }, "3.0");
      }
    }

  },
  config: {
    /**
     * 获得运营主体信息
     */
    getProprietor: function(callback) {
      var key = "setting_cookie_proprietordomain";
      var obj = storage.get(key);
      if (obj && obj != undefined && obj != "" && callback && typeof(callback) == "function") {
        callback(obj);
      }
      var data = {
        "domain": api.domain,
        "terminal": 'pc'
      }
      this.getDictionary(data, key, "core.domain.getproprietordomain", callback);
    },
    /**
     * 获得各个角色配置
     */
    getConfig: function(fkid, fkflag, groupName, moduleKey, callback) {
      var key = "setting_cookie_" + fkid + "_" + fkflag + "_" + groupName + "_" + moduleKey;
      var obj = storage.get(key);
      if (obj && obj != undefined && obj != "" && callback && typeof(callback) == "function") {
        callback(obj);
      }
      var data = {
        "FKId": fkid,
        "FKFlag": fkflag,
        "GroupName": groupName,
        "ModuleKey": moduleKey
      }
      this.getDictionary(data, key, "core.role.config.get", callback);
    },
    /**
     * 获得各角色操作权限
     */
    getAuthorityConfig:function(fkId,fkFlag,token,callback,isFresh = false){
      var key = "setting_cookie_" + fkFlag + "_" + fkId + "_authority";

      // 判断是否需要强制最新的内容,不走缓存
      if (!isFresh) {
        var obj = storage.get(key);
        if (obj && obj != undefined && obj != "" && callback && typeof(callback) == "function") {
          callback(obj);
          return;
        }
      }

      var data = {
        "Token": token,
        // "proprietor":fkFlag,
        // "proprietorId":fkId
      }
      this.getDictionary(data, key, "core.function.authority", (res)=>{
        if(res.Success && (res.Content.ProfileStatus == 0 || res.Content.ProfileStatus == 1 || res.Content.ProfileStatus == 2)){
          router.redirect({
            path:'perfect',
            params:{
              profileStatus:res.Content.profileStatus,
              profileToken:res.Content.ProfileToken
            }
          })
        }else{
          callback(res)
        }
      },'3.0');
    },
    /**
     * 获得运营主体的配置
     */
    getProprietorConfig: function(fkid, fkflag, groupName, moduleKey, callback, isFresh = false) {
      var key = "setting_cookie_" + fkid + "_" + fkflag + "_" + groupName + "_" + moduleKey;

      // 判断是否需要强制最新的内容,不走缓存
      if (!isFresh) {
        var obj = storage.get(key);
        if (obj && obj != undefined && obj != "" && callback && typeof(callback) == "function") {
          callback(obj);
          return;
        }
      }

      var data = {
        "ProprietorId": fkid,
        "GroupName": groupName,
        "ModuleKey": moduleKey
      }
      this.getDictionary(data, key, "core.proprietor.config.get", callback);
    },
    /**
     * 
     */
    getWholesaleConfigs: function(fkid, fkflag, groupName, callback, isFresh = false) {
      var key = "setting_cookie_" + fkid + "_" + fkflag + "_" + groupName;
      var data = {
        "FKId": fkid,
        "FKFlag": fkflag,
        "GroupName": groupName,
        "ProprietorId":fkid
        // "terminalId":5
      }
      if(groupName == 'Wholesale'){
        data.terminalId = 5;
      }
      this.getDictionary(data, key, "core.proprietor.wholesale.get", (res) => {
        callback(this.setModel(res));
      });
    },
    setModel(res) {
      let d = res && res.Success ? (res.Content || {}) : {};
      var model = {
        EnableZeroStockBuy: d.EnableZeroStockBuy == 'True',//是否启用零库存下单
        NotShowProductNoneOffered: d.NotShowProductNoneOffered == 'True', // 是否不显示无货商品按钮
        CommentInfoPageSize: d.CommentInfoPageSize || 5,//评论显示条数
        IsRecharge: (d.IsRecharge != 'False'),//是否允许充值
        IsScanty: (d.IsScanty != 'False'),//是否运行缺货登记
        IsStoreAffirmOrder: (d.IsStoreAffirmOrder == 'True'),//
        IsVisitMallNeedLogin: d.IsVisitMallNeedLogin == 'True',//查看商品详情页是否需要登录
        OpenComment: (d.OpenComment == 'True'),//是否运行商品评论
        OrderLowestBuyMoney: d.OrderLowestBuyMoney,//最小下单金额
        PaySmsVerify: (d.PaySmsVerify == 'True'),//支付是否需要发送短信验证
        PriceDigits: d.PriceDigits || 2,//商品价格 显示小数位
        QuantityDigits: d.QuantityDigits || 0,//商品数量 输入位数
        ShowRetailPrice: (d.ShowRetailPrice == 'True'),//是否显示市场价
        SiteName: d.SiteName || "",
        InvalidMinutes: d.InvalidMinutes||15,//有效时间
        PTInvoiceRate: d.PTInvoiceRate || 0,
        ZZInvoiceRate: d.ZZInvoiceRate || 0,
        FreightMode: d.FreightMode || 1,//运费计算模式：1 标准模式 2 商品指定运费模式
        ShowProductSells: d.ShowProductSells == 'True',//是否显示销量
        AddressAssignDepot: d.AddressAssignDepot == "True", //收货地区匹配仓库
        GoodsDisplayMode: d.GoodsDisplayMode || 0,//商城货品展示模式 0 列表模式，1 橱窗模式 2组合列表模式
        ForbidDeliveryEdit: d.ForbidDeliveryEdit == "True",
        AllOrderAudit: d.AllOrderAudit == "True",//全部订单必须审核
        CODOrderAudit: d.CODOrderAudit == "True",//货到付款订单审核
        OfflinePayOrderAudit: d.OfflinePayOrderAudit == "True",  //线下付款订单审核
        DecimalDigits: d.DecimalDigits || 2,//金额小数位数
        LogoForMobile: d.LogoForMobile||"",//移动logo
        LoginBgPicForMobile: d.LoginBgPicForMobile||"",//移动背景图
        ProprietorWaterMark: d.ProprietorWaterMark ||"",//图片水印
        TitleColorForMobile: d.TitleColorForMobile ||"#e56b14",   //头部颜色  
        MinBalance:d.MinBalance||"100",//最低提现金额
        IsShowLive:(d.IsShowLive == 'True'),  //是否显示直播
        IsShowMinService:(d.IsShowMinService == 'True'),  //是否显示客服
        IsShowPhone:(d.IsShowPhone == 'True'),  //是否显示电话
        ServicePhone:d.ServicePhone || "",     //电话号码
        IsOpenDeliveryTime: d.IsOpenDeliveryTime == 'True',   //开启送货时间
        DeliveryDeadLine:d.DeliveryDeadLine || "",  //当天送货截单时间
        IsNecessityAddress:d.IsNecessityAddress == 'True',//是否选择地址
        IsAddressToReal:d.IsAddressToReal == 'True', // 收货地址验证增强，开启后需要验证地址完整性（省市区和地址详情都需要填写）
        IsEnableSelfPickup:d.IsEnableSelfPickup == 'True',//是否开启买家自提
        PickpointAddress: d.PickpointAddress == 'True', // 自提时，是否需要填写收货地址
        Currency:d.Currency,//货币
        NoLoginShowPrice:d.NoLoginShowPrice == '0',// 0：建议零售价 1：不显示价格
        amapAppKey:d.amapAppKey,//高德地图AppKey
        IsEnableLogisticsExp:(d.IsEnableLogisticsExp == 'True'),//物流快递
        CartName:d.CartName || '购物车',//购物车显示名称
        CloseBuyerCancel:d.CloseBuyerCancel == 'True',//禁止买家取消订单
        FieldDisplayName:d.FieldDisplayName,//字段展示名称
        MClassDisplayField:d.MClassDisplayField,//分类页显示字段 PromotLadder-促销说明  BuyLimit-起订量  PackageSpec-包装规格 Price-建议零售价
        MIntroDefaultTab:Number(d.MIntroDefaultTab),// 0-图片详情，1-详细参数
        MIntroDisplayField:d.MIntroDisplayField,//详情显示字段 ProductCode-商品编号  BarCode-商品条码 
        IsStoreManagerAccount:d.IsStoreManagerAccount,//子账号判断
        Withdrawals:d.Withdrawals == 'True',//预存款 申请提现
        TravellingOrder:d.TravellingOrder == 'True',//线下单据
        GoodsUnitDisplayMode:Number(d.GoodsUnitDisplayMode),// 商品单位模式的配置 0 切换模式 1 列表模式
        LoginType:Number(d.LoginType),//登录方式 0 账户密码 1 短信验证码 2 授权登录
        ContactBottomTip:d.ContactBottomTip,//企业微信底部提示
        ReturnWithoutBuyers:d.ReturnWithoutBuyers == 'True',//无需发货配置
        distributorCustomNo:d.distributorCustomNo ,//极致派服务商编号
        webChatPluginId:d.webChatPluginId ,//极致派插件编号
        IsShowJizhipai: (d.distributorCustomNo != '-1'),//是否显示极致派客服
        NotShowBrandClass: d.NotShowBrandClass == 'True',//是否显示品牌分类
        ShowVendorName: d.ShowVendorName == true, //商品显示供货商名称
        FrontShowStockDetail: d.FrontShowStockDetail == 'True', //是否允许客户点击查看库存分布
        AllowModifyName: d.AllowModifyName == true, //是否允许自主修改客户名称
        AllowModifyHeadIcon: d.AllowModifyHeadIcon == 'True', // 是否允许自主修改客户门头照
        ManagerNotLogin: d.ManagerNotLogin == 'True', //登录是否显示内部员工入口
        NoLoginShowInteraction: d.NoLoginShowInteraction == 'True', // 是否允许未登录进入发现页面
        ShowHistorySearch: d.ShowHistorySearch == 'True', // 是否显示搜索历史记录
        IsStoreDelivery: d.IsStoreDelivery == 'True', // 是否开启商家配送
        AppTemplateConfig: d.AppTemplateConfig || {}, // 商品分类页面样式
        AppQuickTemplateConfig: d.AppQuickTemplateConfig || {}, // 快速下单页面样式
        LogisticsModeDisplayName: d.LogisticsModeDisplayName || '', // 订单 物流方式名称设置
        BGColorForMobile: d.BGColorForMobile || '#ffffff', // 主要页面背景颜色（首页，商品列表，购物车，个人中心等）
      };
      return model;
    },
    getDictionary: function(data, key, action, callback,version) {
      util.post(action, data, function(res) {
        res = res.data;
        if (callback != undefined && typeof(callback) == "function") {
          storage.put(key, res, 24 * 60 * 60);
          callback(res);
        }
      }, (version||"2.0"), null, false);
    },
    /**
    * 获取积分规则
    */
    getIntegralRule(fkid,fkway,callback, isFresh = false) {
      var key = "setting_cookie_integralrule" + fkid + "_" + fkway;
      var obj = storage.get(key);
      if (!isFresh && obj && obj != undefined && obj != "" && callback && typeof (callback) == "function") {
        callback(obj);
        return;
      }

      var data = {
        "ProprietorId": fkid,
        "FKWay": fkway
      }
      util.post("integral.integralrule.get", data, function (res) {
        res = res.data;
        if (callback != undefined && typeof (callback) == "function") {
          storage.put(key, res, 24 * 60 * 60);
          callback(res);
        }
      }, "3.0", null, false);
    },
    /**
    * 头像上传
    */
    uploadUserImg(data,callback){
      var entity = authorize.getEntity() || authorize.getDefault();
      var data = {
        Token: entity.manager.Token,
        FaceUrl:data
      }
      util.post("store.manager.updateface", data, function (res) {
        res = res.data;
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      }, "3.1", null, false);
    },
    getAvatar(data,callback){
      var entity = authorize.getEntity() || authorize.getDefault();
      var data = {
        Token: entity.manager.Token,
        storeId:entity.fkId,
        Proprietor: data.proprietor,
        ProprietorId: data.proprietorId,
      }
      util.post("store.shop.getinfo", data, function (res) {
        res = res.data;
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      }, "3.0", null, false);
    },
    /**
    * 获取往来账url
    */
    getWlzUrl(location, callback){
      var entity = authorize.getEntity() || authorize.getDefault();
      var data = {
        Token: entity.manager.Token,
        cutomerId: entity.fkId,
        returnUrl: location
      }
      util.post("Sync.qct.wlzurl", data, function (res) {
        res = res.data;
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      }, "3.0", null, false);
    },
    /*首页更新*/
    indexCompare(data,callback){
      var data = {
        pageId:data.pageId,
        PublishTime:data.PublishTime
      };
      util.post("theme.publish.compare",data,function(res){
        res = res.data;
        if (callback != undefined && typeof (callback) == "function") {
          callback(res);
        }
      }, "3.0", null, false)
    },
  },
  /**加载地区 */
  area: { 
    load(callback) {
      var key = "core_cities";
      var obj = storage.get(key);
      if (obj && obj != undefined && obj != "" && callback && typeof(callback) == "function") {
        callback(obj);
        return;
      }
      util.post("core.regindic.get", { isContainAreaCode:1}, function(res) {
        res = res.data;
        if (callback != undefined && typeof(callback) == "function") {
          if(res.Success){
            storage.put(key, res, 0);
          }

          callback(res);
        }
      }, "3.0");
    },
    /**获得缓存定位 */
    getCacheLocation(){
      let location_key= "location_key";
      let location_obj= storage.get(location_key);
      if (location_obj && Object.keys(location_obj).length > 0) {
        return location_obj;
      }
      return { Code: ""};
    },
    /**设置缓存定位 */
    setCacheLocation(v){
      let location_key = "location_key";
      storage.put(location_key,v);
    },
    /**移除缓存定位 */
    removeCacheLocation(){
      let location_key = "location_key";
      storage.remove(location_key);
    }
  },
  account: {
    isLogin(role) {
      return authorize.isLogin(role);
    },
    exchange_for_token: function(role, token, callback) {
      var data = {
        PassportToken: token
      }
      util.post("account." + role + ".exchangefor.token", data, function(res) {
        res = res.data;
        if (res.Success) {
          var param = {
            PassportToken: res.Content
          }
          util.post("account." + role + ".token.login", param, function(res) {
            res = res.data;
            if (res.Success && res.Content) {
              authorize.setCookie(role, res.Content);
              if(callback && typeof(callback) == 'function'){
                callback(true, res.Content);
              }
            }else if(callback && typeof(callback) == 'function'){
              callback(false, res);
            }
          }, "3.0", null, false);
        }else if(callback && typeof(callback) == 'function'){
          callback(false, res);
        }
      }, "3.0", null, false);



    },
    get_upload_token:function(datas,proprietor_id,callback){
      if(!datas.type)return;
      let role=authorize.loginRole();
      let entity=authorize.getEntity(role);
      let id = entity == null ? 0 : entity.fkId;
      // if(entity==null) {
      //   if(typeof(callback)=="function"){
      //     callback("");         
      //   }
      //   return;
      // }
      let key="upload_token"+proprietor_id+"_"+id;
      let obj=storage.get(key);
      if(obj&&obj!=""){
        if(typeof(callback)=="function"){
          callback(obj);
        }
        return;
      }
      var header = {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
        'Platform': 'Weapp'
      };
      var param = {
        ProprietorId:proprietor_id,
        UploadType:datas.type || ''
      };
      if(entity){
        param.Token = entity.manager.Token
      }else{
        param.ProfileToken = datas.profileToken
      }
      util.post("material.authorize.get", param, function (res) {
        res=res.data;
        if (res.Success) {
          let token=res.Content?res.Content.ufs_token:"";
          if (callback != undefined && typeof (callback) == "function") {
            callback(token);
          }
          storage.put(key,token);
        }
      }, "3.1", null, true);
      // wx.request({
      //   url: api.gwDomain+"/upload/api",
      //   data:{
      //     method: "auth.token.generate",
      //     proprietor_id: proprietor_id,
      //     user_id: id   //entity.fkId
      //    },
      //   header: header,
      //   method: 'POST',
      //   responseType: 'text',
      //   success: res => {
      //     res=res.data;
      //     let token=res.content?res.content.token:"";
      //     if (callback&&typeof(callback) == "function") { 
                     
      //       callback(token);
      //     }
      //     storage.put(key,token);
      //   },
      //   fail: function (res) {
      //     console.log(res.errMsg);
      //   },
      //   complete: function (res) {
      //     // todo
      //   },
      // })
    },
    loginOut:function(){
      authorize.loginOut();
    }
  },

  wholesaleSettings:{
   getConfig(){
     return WholesaleSettings.getConfig() || WholesaleSettings.getDefault();
   },
   setConfig(data){
     WholesaleSettings.setConfig(data);
   }
  },
  category:{
    load(fkid, fkflag,partId,callback,isFresh=false) {
      var key = "all_category_" + fkid+"_"+fkflag;
      var obj = storage.get(key);
      if (!isFresh && obj && obj != undefined && obj != "" && callback && typeof (callback) == "function") {
        callback(obj);
        return;
      }
      var entity = authorize.getEntity() || authorize.getDefault();
      var param = {
        Proprietor: fkflag,
        ProprietorId: fkid,
        FKFlag: fkflag,
        FKId: fkid,
        UserId:entity.fkId,
        Condition: "<ParentId>" + partId + "</ParentId><IsUseCustom>false</IsUseCustom>",
        Token: entity.manager.Token
      };

      util.post("mall.category.tree", param, function (res) {
        res = res.data;
        if (res.Success) {
          storage.put(key, res, 0);
          if (callback != undefined && typeof (callback) == "function") {
            callback(res);
          }
        }
      }, "3.1", null, true);
    }
  },
  //分享设置内容
  share:{
    getinfo:function(data,isH5,callback){
      var entity = authorize.getEntity() || authorize.getDefault();
      if(entity&&entity.fkId>0&&entity.manager.ManagerId>0){
        data.Scene=entity.fkFlag+"_"+entity.fkId+"_"+entity.manager.ManagerId;
      } 
      if(!isH5){
        data.FKFlag = entity.fkFlag;
        data.FKId = entity.fkId;
      }
      util.post("core.share.mapper", data, function(res) {
        res = res.data;
        if (res.Success) {
          if (callback != undefined && typeof (callback) == "function") {
            let content = res.Content[0]
            // 分享图片改为宽高比5:4的图片
            if (api.enableOss && content.ImgSrc) {
              let h = 400
              let w = 500
              content.ImgSrc = content.ImgSrc + "?x-oss-process=image/resize,m_pad,h_" + h + ",w_" + w
            }
            callback(content);
          }
        }
      }, "3.0", null, false);
    }
  }
}